
package com.sfdlJPush.utils;

import android.app.Activity;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.sfdlJPush.controller.LoginActivity;
import com.sfdlJPush.controller.MainApplication;
import com.sfdlJPush.model.User;

/**
 *  用户信息管理类
 * @author yushilong
 *
 */
public class UserInfoManage
{
    private User user;
    private boolean isLogined;
    private static UserInfoManage _instance;
    public static final String companyId = "5";

    /**
     * 初始化用户信息
     * 
     * @param userString
     */
    public void saveUser(String userString)
    {
        if (!TextUtils.isEmpty(userString))
        {
            isLogined = true;
            user = new Gson().fromJson(userString, User.class);
            B5MCacheManage.getInstance().saveObject(userString, "");
        }
        else
        {
            throw new NullPointerException("user is null");
        }
    }

    /**
     * 清除数据，例如登出操作
     */
    public void clearData()
    {
        user = null;
        isLogined = false;
    }

    public User getUser()
    {
        if (isLogined)
        {
            if (user == null)
            {
                String userString = B5MCacheManage.getInstance().readObject("");
                if (!TextUtils.isEmpty(userString))
                {
                    return new Gson().fromJson(userString, User.class);
                }
            }
            else
            {
                return user;
            }
        }
        return null;
    }

    public boolean isLogined()
    {
        return isLogined;
    }

    public static UserInfoManage getInstance()
    {
        synchronized (UserInfoManage.class)
        {
            if (_instance == null)
            {
                _instance = new UserInfoManage();
            }
        }
        return _instance;
    }

    public boolean checkIsLogined(Activity activity)
    {
        if (!isLogined)
        {
            B5MActivityHelper.startActivity(activity, LoginActivity.class);
            return true;
        }
        return false;
    }

    public static String getLang()
    {
        return B5MPreferenceHelper.readStringValue(MainApplication.getInstance(), B5MPreferenceKeys.LANGUAGE, "zh");
    }
}
